import * as express from 'express';
import * as path from 'path';
import {Server} from 'ws';

/*创建express服务*/
const app = express();

export class Product {
    constructor(
        public id?: number,
        public title?: string,
        public price?: number,
        public rating?: number,
        public desc?: string,
        public categories?: Array<string>
    ) {
    }
}

export class Comment {
    constructor(
        public id?: number,
        public productId?: number,
        public timestamp?: string,
        public user?: string,
        public rating?: number,
        public content?: string
    ) {

    }
}

const comments: Comment[] = [
    new Comment(1, 1, "2013-02-02 12:12:13", '张三1', 11, 'ad'),
    new Comment(2, 1, "2013-02-02 12:12:13", '张三2', 11, 'sad'),
    new Comment(3, 1, "2013-02-02 12:12:13", '张三3', 11, 'dd'),
    new Comment(4, 2, "2013-02-02 12:12:13", '张三4', 11, 'ddd'),
    new Comment(5, 2, "2013-02-02 12:12:13", '张三5', 11, 'sss'),
];

const products: Product [] = [
    new Product(1, '商品1', 13, 5, '飞机是一种快速飞行的工具，他能搭载许多乘客！', ['硬件设备', '电子产品', '图书']),
    new Product(2, '商品2', 123, 2.5, '飞机是一种快速飞行的工具，他能搭载许多乘客！', ['图书']),
    new Product(3, '商品3', 23, 3.5, '飞机是一种快速飞行的工具，他能搭载许多乘客！  ', ['硬件设备', '图书']),
    new Product(4, '商品4', 113, 2.5, '飞机是一种快速飞行的工具，他能搭载许多乘客！', ['电子产品']),
    new Product(5, '商品5', 133, 2.5, '飞机是一种快速飞行的工具，他能搭载许多乘客！', ['硬件设备']),
];
/*app.get("/", (req, res) => {
    res.send("This is a express service!");
})*/

app.use('/', express.static(path.join(__dirname,'..','client')));

app.get("/api/products", (req, res) => {
    /*res.send(JSON.stringify(products));*/
    res.json(products);
})

app.get("/api/product/:id", (req, res) => {
    res.json(products.find((product) => product.id == req.params.id));
})

app.get('/api/product/:id/comments', (req, res) => {
    res.json(comments.filter((comment: Comment) => comment.productId = req.params.id))
})
const server = app.listen(8000, 'localhost', () => {
    console.log("服务器已经启动");
});

const wsServer = new Server({
    port: 8085
})
wsServer.on("connection",
    websocket => {
        websocket.send("这个消息是服务器主动推送的");
        websocket.on("message", message => {
            console.log("接收到消息:" + message)
        })
    })

setInterval(() => {
    if (wsServer.clients) {
        wsServer.clients.forEach(client => {
            client.send("这是定时推送!");
        })
    }
}, 2000)